package com.robot.orders.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lin
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Passing through the JwtInterceptor");
        //无论如何都放行。具体能不能操作还是在具体的操作中去判断。
        //拦截器只是负责把请求头中包含token的令牌进行解析验证。
        String firstString = "ROBOT ";
        String header = request.getHeader("AUTH");
        if (header != null && !"".equals(header)) {
            //如果包含有Authorization头信息，就对其进行解析
            if (header.startsWith(firstString)) {
                //得到令牌
                String token = header.substring(5);
                //对令牌进行验证
                String adminRoles = "admin";
                String agentRoles = "agent";
                String merchantRoles = "merchant";
                String memberRoles = "member";
                try {
                    Claims claims = jwtUtil.parseJwt(token);
                    String roles = (String) claims.get("roles");
                    if (adminRoles.equals(roles)) {
                        request.setAttribute("robot_admin", claims);
                    }
                    if (agentRoles.equals(roles)) {
                        request.setAttribute("robot_agent", claims);
                    }
                    if (merchantRoles.equals(roles)) {
                        request.setAttribute("robot_merchant", claims);
                    }
                    if (memberRoles.equals(roles)) {
                        request.setAttribute("robot_member", claims);
                    }
//                    Logon expires, please login again
                } catch (Exception e) {
                    response.setStatus(401);
                    System.out.println("Token incorrect");
                    throw new RuntimeException("401");
                }
            }
        }
        System.out.println("Passing through the JwtInterceptor2");
        return true;
    }
}
